const METHOD = {
  GET: 'GET',
  POST: 'POST',
  PUT: 'PUT',
  DELETE: 'DELETE'
}

class Request {
  _header = {
    token: null
  }
  _baseUrl = null

  interceptors = []

  constructor() {
    const token = wx.getStorageSync('token')
    if (token) {
      this._header.token = token
    }
  }

  intercept(res, resolve, reject) {
    var data = res
    this.interceptors.forEach(f => {
      var temp = f(data)
      if (temp.error) {
        reject(temp.error)
        return
      } else {
        data = temp.data
      }
    })
    resolve(data)
  }

  request({ url, method, header = {}, data }) {
    return new Promise((resolve, reject) => {
      var urlStr
      if (url.indexOf('http') != -1 || url.indexOf('https') != -1) {
        urlStr = url
      }else {
        urlStr = (this._baseUrl || '') + url
      }
      wx.request({
        url: urlStr,
        method: method || METHOD.GET,
        data: data,
        header: {
          ...this._header,
          ...header
        },
        success: res => this.intercept(res, resolve, reject),
        fail: res => {
          reject({ errorCode: res.statusCode || -1, errorMessage: '无网络或配置异常' })
        }
      })
    })
  }
  upload({ url, filePath, name }) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: (this._baseUrl || '') + url,
        filePath: filePath,
        name: filePath,
        success: res => this.intercept(res, resolve, reject),
        fail: res => {
          reject({ errorCode: res.statusCode || -1, errorMessage: '无网络或配置异常' })
        }
      })
    })
  }

  get(url, data, header) {
    return this.request({ url, method: METHOD.GET, header, data })
  }
  post(url, data, header) {
    return this.request({ url, method: METHOD.POST, header, data })
  }
  put(url, data, header) {
    return this.request({ url, method: METHOD.PUT, header, data })
  }
  delete(url, data, header) {
    return this.request({ url, method: METHOD.DELETE, header, data })
  }
  upload(url, filePath, name) {
    return this.upload({ url, filePath, name })
  }

  token(token) {
    this._header.token = token
    return this
  }
  header(header) {
    this._header = header
    return this
  }
  baseUrl(baseUrl) {
    this._baseUrl = baseUrl
    return this
  }
  //{error,data}
  interceptor(f) {
    if (typeof f === 'function') {
      this.interceptors.push(f)
    }
    return this
  }
}
//全局共享一个Request实例，使用这个要求接口高度统一
export default new Request
//export {METHOD}